package cc.eddic.pratice.programmingparadigms.emp01array.impl;

import cc.eddic.pratice.programmingparadigms.Employee;
import cc.eddic.pratice.programmingparadigms.Result;
import cc.eddic.pratice.programmingparadigms.emp01array.EmployeeStatisticsService;

import java.util.function.Function;

/**
 * 谷常生实现的版本
 */
public class StatisticsGcsImpl extends ReaderGcsImpl implements EmployeeStatisticsService {
    /**
     * 按照性别统计
     *
     * @param employees Employee 数组
     * @return 统计结果数组
     */
    @Override
    public Result[] pivotByGender(Employee[] employees) {
        return countBy(employees, Employee::getGender);
    }


    /**
     * 按照部门统计
     *
     * @param employees Employee 数组
     * @return 统计结果数组
     */
    @Override
    public Result[] pivotByDepartment(Employee[] employees) {
        return countBy(employees, Employee::getDepartment);
    }

    /**
     * 按照职位统计
     *
     * @param employees Employee 数组
     * @return 统计结果数组
     */
    @Override
    public Result[] pivotByJobTitle(Employee[] employees) {
        return countBy(employees, Employee::getJobTitle);
    }

    private Result[] countBy(final Employee[] employees, Function<Employee, String> fieldExtractor) {
        int index = 0;
        Result[] results = new Result[employees.length];
        for (Employee employee : employees) {
            String key = fieldExtractor.apply(employee);

            boolean isFound = false;
            // 如果已经存在，则加 1
            for (Result result : results) {
                if (null == result) {
                    break;
                }
                if (result.getKey().equals(key)) {
                    isFound = true;
                    result.inc();
                }
            }
            // 如果不存在，添加，初始值为 1
            if (!isFound) {
                results[index++] = new Result(key);
            }
        }
        // 返回实际数量的数组
        Result[] newResults = new Result[index];
        for (int i = 0; i < index; i++) {
            newResults[i] = results[i];
        }
        // 数量倒排序
        bubbleSort(newResults);
        return newResults;
    }

    protected void bubbleSort(final Result[] results) {
        for (int i = 0; i < results.length; i++) {
            for (int j = 0; j < results.length - i - 1; j++) {
                if (results[j].getCount() < results[j + 1].getCount()) {
                    Result temp = results[j];
                    results[j] = results[j + 1];
                    results[j + 1] = temp;
                }
            }
        }
    }
}
